package user

import (
	// "fmt"
	// "regexp"

	"Web-Shop/models"
	"strconv"

	// "fmt"
	// "Web-Shop/modules/utils"
	// "github.com/astaxie/beego/utils"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
)

func (c *UserController) ShowUser() {
	c.Layout = "page/user_center/layout.html"
	c.TplName = "page/user_center/info.html"

	if !c.IsLogin {
		c.Redirect("/login.html", 302)
	}
	addr := &models.Address{}
	historyGoods := make([]*models.GoodsSKU, 0)
	addr.Read(addr, c.User)

	conn, err := redis.Dial("tcp", "47.111.181.52:6379")
	if err != nil {
		logs.Error("redis连接失败")
	} else {
		defer conn.Close()
		rep, err := conn.Do("lrange", "history_"+strconv.Itoa(c.User.Id), 0, 4)
		goodsIDs, _ := redis.Ints(rep, err)
		for _, v := range goodsIDs {
			goods, _ := (&models.GoodsSKU{Id: v}).Read()
			historyGoods = append(historyGoods, goods)
		}
	}
	c.Data["historyGoods"] = historyGoods
	c.Data["addr"] = addr.Addr

}

func (c *UserController) ShowOrders() {
	c.Layout = "page/user_center/layout.html"
	c.TplName = "page/user_center/order.html"

	//获取订单表的数据
	o := orm.NewOrm()
	var orderInfos []models.OrderInfo
	o.QueryTable("OrderInfo").RelatedSel("User").Filter("User__Id", c.User.Id).All(&orderInfos)

	goodsBuffer := make([]map[string]interface{}, len(orderInfos))

	for index, orderInfo := range orderInfos {

		var orderGoods []models.OrderGoods
		o.QueryTable("OrderGoods").RelatedSel("OrderInfo", "GoodsSKU").Filter("OrderInfo__Id", orderInfo.Id).All(&orderGoods)

		temp := make(map[string]interface{})
		temp["orderInfo"] = orderInfo
		temp["orderGoods"] = orderGoods

		goodsBuffer[index] = temp

	}

	c.Data["goodsBuffer"] = goodsBuffer
}

func (c *UserController) ShowAddress() {
	c.Layout = "page/user_center/layout.html"
	c.TplName = "page/user_center/address.html"
	addressSlice := []*models.Address{
		&models.Address{},
	}
	addressSlice[0].Read(&addressSlice, c.User)
	logs.Error("addslicke", addressSlice)
	c.Data["address"] = addressSlice
}

func (c *UserController) EditAddress() {
	defer c.Redirect("/address", 302)

	receiver := c.GetString("receiver")
	addr := c.GetString("addr")
	Zipcode := c.GetString("zipCode")
	phone := c.GetString("phone")

	if receiver == "" || addr == "" || Zipcode == "" || phone == "" {
		c.FlashNotice("数据不完整，请重新填写")
		return
	}

	address := &models.Address{
		User:      c.User,
		Receiver:  receiver,
		Addr:      addr,
		Zipcode:   Zipcode,
		Phone:     phone,
		Isdefault: true,
	}
	if err := address.Insert(); err != nil {
		logs.Error(err)
		return
	}
}
